﻿Imports System.Text.RegularExpressions
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography


Public Class Outils
    Enum TypeRegex
        TelQuebec
        TelFrance
        Courriel
        CodePostalQc
        CodePostalFr
        Nom
        adresse
        NAS
    End Enum
    Enum TypeEvenement
        Activite
        Accompagnement
        Tache
    End Enum

    Public Class Validation

        Enum TypeRegex
            TelQuebec
            TelFrance
            Courriel
            CodePostalQc
            CodePostalFr
            Nom
            adresse
            NAS
        End Enum


        Public Shared Function CheckRegex(ByVal RegexType As TypeRegex, ByVal strValidate As String) As Boolean
            Select Case RegexType
                Case TypeRegex.Courriel
                    Return Regex.IsMatch(strValidate, "\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b")
                Case TypeRegex.TelFrance
                    Return Regex.IsMatch(strValidate, "^0[1-6]{1}(([0-9]{2}){5})|((\s[0-9]{2}){5})|((-[0-9]{2}){5})|((-[0-9]{2}){5})$")
                Case TypeRegex.CodePostalQc
                    Return Regex.IsMatch(strValidate, "^[a-z]{1}[0-9]{1}[a-z]{1}[0-9]{1}[a-z]{1}[0-9]{1}$")
                Case TypeRegex.TelQuebec
                    Return Regex.IsMatch(strValidate, "\(?\d{3}\)?\s\d{3}-\d{4}")
                Case TypeRegex.Nom
                    Return Regex.IsMatch(strValidate, "^([A-ZÉÈéèàÀäÄëËïÏêÊîÎâÂçÇÔôa-z\.'\- ]+)$")
                Case TypeRegex.adresse
                    Return Regex.IsMatch(strValidate, "^([0-9]+ [A-ZÉÈéèàÀäÄëËïÏêÊîÎâÂçÇÔôa-z'\- ]+)$")
                Case TypeRegex.NAS
                    Return Regex.IsMatch(strValidate, "^[0-9]{3}[0-9]{3}[0-9]{3}$")
                Case TypeRegex.CodePostalFr
                    Return Regex.IsMatch(strValidate, "^[0-9]{5}$")
            End Select


        End Function

        Public Shared Function CapFirstChar(ByVal strText As String) As String
            If Not strText.Trim = "" Then
                Return (Char.ToUpper(strText(0)) + strText.Substring(1))
            End If
            Return strText
        End Function

    End Class

    Public Class ErrorProviderFunctions
        Public Enum ErrorType
            Critical
            Warning
            Info
        End Enum

        Public Shared Sub AddError(ByVal oDestination As Control, ByRef oControl As Control, ByVal strMessage As String, Optional ByVal bDispatchToActivityBox As Boolean = True)
            If Not TypeOf (oDestination) Is ContainerInterface Then
                While Not TypeOf (oDestination.Parent) Is ContainerInterface
                    oDestination = oDestination.Parent
                End While
                CType(oDestination.Parent, ContainerInterface).AddErrorToLocalErrorProvider(oControl, strMessage, bDispatchToActivityBox)
            Else
                CType(oDestination, ContainerInterface).AddErrorToLocalErrorProvider(oControl, strMessage, bDispatchToActivityBox)
            End If
        End Sub


        Public Shared Sub RemoveError(ByVal oDestination As Control, ByRef oControl As Control)
            If Not TypeOf (oDestination) Is ContainerInterface Then
                While Not TypeOf (oDestination.Parent) Is ContainerInterface
                    oDestination = oDestination.Parent
                End While
                CType(oDestination.Parent, ContainerInterface).RemoveErrorToLocalErrorProvider(oControl)
            Else
                CType(oDestination, ContainerInterface).RemoveErrorToLocalErrorProvider(oControl)
            End If
        End Sub



        Public Shared Sub DispatchToActivityBox(ByVal MessageType As ErrorType, ByVal p_strError As String, Optional ByVal oObject As Control = Nothing)
            MainForm.PreviousStatus.Text = p_strError

            Select Case MessageType
                Case ErrorType.Info
                    MainForm.PreviousStatus.Image = My.Resources.Images.check
                Case ErrorType.Warning
                    MainForm.PreviousStatus.Image = My.Resources.Images.warning
                Case ErrorType.Critical
                    MainForm.PreviousStatus.Image = My.Resources.Images.critical
                Case Else
                    MainForm.PreviousStatus.Image = Nothing
            End Select


            If IsNothing(oObject) Then
                MainForm.PreviousStatus.DropDownItems.Add("(" & Now.ToLongTimeString & ") " & p_strError, MainForm.PreviousStatus.Image)
            Else
                Dim CustEventArgs As New CustomEventArgs
                CustEventArgs.ControlEvent = oObject
                MainForm.PreviousStatus.DropDownItems.Add("(" & Now.ToLongTimeString & ") " & p_strError, MainForm.PreviousStatus.Image, Function(obj As Object, e As EventArgs) SetFocus(oObject, CustEventArgs))
                'PreviousStatus.DropDownItems.Add("(" & Now.ToLongTimeString & ") " & p_strError, PreviousStatus.Image, CType(Sub(obj As Object, e As EventArgs) SetFocus(oObject), EventHandler))
            End If

            If MainForm.PreviousStatus.DropDownItems.Count > 15 Then
                MainForm.PreviousStatus.DropDownItems.RemoveAt(0)
            End If

            If Not ErrorType.Info = MessageType Then
                'iDisplayActivityBoxDelay = 40
                ' ActivityBoxCounter.Start()
                MainForm.PreviousStatus.ShowDropDown()
            End If

        End Sub
        Private Shared Function SetFocus(ByVal sender As Object, ByVal e As CustomEventArgs) As Boolean
            'PreviousStatus.DropDownItems(oObject)

            GetParentOfParent(e.ControlEvent)
            If Not e.ControlEvent Is Nothing Then
                If TypeOf (e.ControlEvent) Is Button Then
                    e.ControlEvent.Focus()
                End If
            Else
                e.ControlEvent.Focus()
            End If
            Return True
        End Function

        Private Shared Sub GetParentOfParent(ByVal oObject As Control)
            MainForm.oList = New List(Of Control)
            GetAllControlsHierarchies(MainForm, MainForm.oList)
            If MainForm.oList.Contains(oObject) Then
                If oObject.Parent Is MainForm Then
                    oObject.Focus()
                ElseIf TypeOf (oObject.Parent) Is TabPage Then
                    If Not IsNothing(oObject.Parent.Parent) Then
                        CType(oObject.Parent.Parent, TabControlEx).SelectedTab = oObject.Parent
                        GetParentOfParent(oObject.Parent)
                    End If
                Else
                    GetParentOfParent(oObject.Parent)
                End If
            End If

        End Sub

        ''' <summary>
        ''' Get all controls within current control
        ''' </summary>
        ''' <remarks></remarks>
        Private Shared Sub GetAllControlsHierarchies(ByVal p_oControl As Control, ByVal p_oControls As List(Of Control))
            If p_oControl Is Nothing Then Return

            p_oControls.Add(p_oControl)

            For Each oControl As Control In p_oControl.Controls
                GetAllControlsHierarchies(oControl, p_oControls)
            Next
        End Sub

        ''' <summary>
        ''' Ajoute un champ de type information dans le bas
        ''' </summary>
        ''' <param name="strMessage"></param>
        ''' <remarks></remarks>
        Public Shared Sub SetInfo(ByVal strMessage As String)
            DispatchToActivityBox(Outils.ErrorProviderFunctions.ErrorType.Info, strMessage)
        End Sub




    End Class

    Public Class GestionImage
        Public Shared Function GetImageFromDB(ByVal p_ImageID As Integer) As Drawing.Image
            Dim ImageToReturn As System.Drawing.Image = Nothing

            Dim ImageBytes() As Byte = (From u In (New DBMainContext).Image Where u.ID = p_ImageID Select u.Valeur).FirstOrDefault.ToArray
            Dim otest As New MemoryStream(ImageBytes)

            ImageToReturn = System.Drawing.Image.FromStream(otest)

            Return ImageToReturn
        End Function


        ''' <summary>
        ''' Save image to database
        ''' </summary>
        ''' <param name="p_FilePath"></param>
        ''' <returns>Id of the image in the database</returns>
        ''' <remarks></remarks>
        Public Shared Function SaveImageToDB(ByVal p_FilePath As String) As Integer
            If Not p_FilePath = "" Then
                Dim oContext As New DBMainContext



                Dim fileDetail As IO.FileInfo = My.Computer.FileSystem.GetFileInfo(p_FilePath)
                'MsgBox(fileDetail.Length)
                Dim newImage As Drawing.Image
                Dim o() As Byte = File.ReadAllBytes(p_FilePath)

                Dim otest As New MemoryStream(o)

                Dim oImageTemp As Drawing.Image = Drawing.Image.FromStream(otest)
                newImage = oImageTemp

                '278, 259

                If oImageTemp.Size.Height > 278 And Math.Max(oImageTemp.Size.Height, oImageTemp.Size.Width) = oImageTemp.Size.Height Then
                    Dim oImageRatio As Decimal = oImageTemp.Size.Width / oImageTemp.Size.Height
                    Dim oNewSize As New Size(278 * oImageRatio, 278)
                    Dim bmp As Bitmap = New Bitmap(oNewSize.Width, oNewSize.Height)
                    Using g As Graphics = Graphics.FromImage(bmp)
                        g.DrawImage(oImageTemp, 0, 0, oNewSize.Width, oNewSize.Height)
                    End Using
                    newImage = bmp

                End If

                If oImageTemp.Size.Width > 259 And Math.Max(oImageTemp.Size.Height, oImageTemp.Size.Width) = oImageTemp.Size.Width Then
                    Dim oImageRatio As Decimal = oImageTemp.Size.Width / oImageTemp.Size.Height
                    Dim oNewSize As New Size(259, 259 / oImageRatio)
                    Dim bmp As Bitmap = New Bitmap(oNewSize.Width, oNewSize.Height)
                    Using g As Graphics = Graphics.FromImage(bmp)
                        g.DrawImage(oImageTemp, 0, 0, oNewSize.Width, oNewSize.Height)
                    End Using
                    newImage = bmp
                End If
                oImageTemp = newImage

                Dim otest2 As New MemoryStream()
                Select Case p_FilePath.Substring(p_FilePath.LastIndexOf("."))
                    Case ".png"
                        newImage.Save(otest2, Drawing.Imaging.ImageFormat.Png)
                    Case ".jpeg", ".jpg"
                        newImage.Save(otest2, Drawing.Imaging.ImageFormat.Jpeg)
                    Case ".gif"
                        newImage.Save(otest2, Drawing.Imaging.ImageFormat.Gif)
                    Case ".bmp"
                        newImage.Save(otest2, Drawing.Imaging.ImageFormat.Bmp)
                    Case Else
                        newImage.Save(otest2, Drawing.Imaging.ImageFormat.Jpeg)
                End Select

                Dim oImageTemp2 As Drawing.Image = Drawing.Image.FromStream(otest2)


                'MsgBox(oImageTemp2.Size)

                Dim oImage As New Image With {.Nom_Image = p_FilePath.Split("\")(p_FilePath.Split("\").Count - 1), .Valeur = otest2.GetBuffer()}

                oContext.Image.InsertOnSubmit(oImage)

                oContext.SubmitChanges()

                Return oImage.ID
            Else
                Return 0
            End If

        End Function

        Public Shared Function GetImageFromFileDialog() As String

            Dim ochooser As New OpenFileDialog
            ochooser.Filter = "Jpeg(.jpg)|*.jpg;*.jpeg|Gif(.gif)|*.gif|Png(.png)|*.png|Tous(*)|*.*"
            ochooser.ShowDialog()
            If Not ochooser.FileName = "" Then
                Return ochooser.FileName
            Else
                Return ""
            End If


        End Function

    End Class


    Public Class MotDePasse
        Public Shared Function GenerateHash(ByVal SourceText As String) As String
            'Create an encoding object to ensure the encoding standard for the source text
            Dim Ue As New UnicodeEncoding()
            'Retrieve a byte array based on the source text
            Dim ByteSourceText() As Byte = Ue.GetBytes(SourceText)
            'Instantiate an MD5 Provider object
            Dim Md5 As New MD5CryptoServiceProvider()
            'Compute the hash value from the source
            Dim ByteHash() As Byte = Md5.ComputeHash(ByteSourceText)
            'And convert it to String format for return
            Return Convert.ToBase64String(ByteHash)
        End Function
    End Class

    Public Class TabControl

        Public Shared Sub RemoveSelectedTab()
            MainForm.tcMain.RemoveSelectedTab()
        End Sub

        Public Shared Sub RemoveTabByName(ByVal strNom As String)
            MainForm.tcMain.RemoveSelectedTabByName(strNom)
        End Sub

        Public Shared Sub RenameSelectedTab(ByVal strNouveauNom As String)
            MainForm.tcMain.RenameSelectedTab(strNouveauNom)
        End Sub

    End Class

    Public Class ParametreApplication

        Public Shared ReadOnly Property DebutDeLaJournee() As Integer
            Get
                Dim oStrValue As String
                oStrValue = (From u In (New DBMainContext).Parametre Where u.Nom_Param = "DebutDeLaJournee" Select u.Valeur_Param).FirstOrDefault

                Return CInt(oStrValue.Split(":")(0)) * 4 + CInt(oStrValue.Split(":")(1)) / 15
                'Return (From u In (New DBMainContext).Parametre Where u.Nom_Param = "DebutDeLaJournee" Select CInt(u.Valeur_Param)).FirstOrDefault
            End Get

        End Property

        Public Shared ReadOnly Property CouleurDispo() As Color
            Get
                Return GetColorHex((From u In (New DBMainContext).Parametre_Couleur Where u.Nom_Param = "CouleurDispo" Select u.Valeur_CouleurHex).FirstOrDefault)
            End Get

        End Property

        Public Shared ReadOnly Property CouleurNonDispo() As Color
            Get
                Return GetColorHex((From u In (New DBMainContext).Parametre_Couleur Where u.Nom_Param = "CouleurNonDispo" Select u.Valeur_CouleurHex).FirstOrDefault)
            End Get

        End Property

        Public Shared ReadOnly Property CouleurActivite() As Color
            Get
                Return GetColorHex((From u In (New DBMainContext).Parametre_Couleur Where u.Nom_Param = "CouleurActivite" Select u.Valeur_CouleurHex).FirstOrDefault)
            End Get

        End Property

        Public Shared ReadOnly Property CouleurAccompagnement() As Color
            Get
                Return GetColorHex((From u In (New DBMainContext).Parametre_Couleur Where u.Nom_Param = "CouleurAccompagnement" Select u.Valeur_CouleurHex).FirstOrDefault)
            End Get

        End Property

        Public Shared ReadOnly Property CouleurTache() As Color
            Get
                Return GetColorHex((From u In (New DBMainContext).Parametre_Couleur Where u.Nom_Param = "CouleurTache" Select u.Valeur_CouleurHex).FirstOrDefault)
            End Get
        End Property



        Private Shared Function GetHexColor(ByVal colorObj As System.Drawing.Color) As String
            Return "#" & IIf(Hex(colorObj.R) = "", "00", Hex(colorObj.R)) & IIf(Hex(colorObj.G) = "", "00", Hex(colorObj.G)) & IIf(Hex(colorObj.B) = "", "00", Hex(colorObj.B))
        End Function

        Private Shared Function GetColorHex(ByVal strHex As String) As Color
            Return ColorTranslator.FromHtml(strHex.PadRight(7, "0"))
        End Function

    End Class

    Public Class Horaire
        Public Shared Function GetBinFromHeure(ByVal Time As Date) As Integer
            Dim oStrValue As String
            oStrValue = Time.ToString("HH:mm")
            Return CInt(oStrValue.Split(":")(0)) * 4 + Math.Floor(CInt(oStrValue.Split(":")(1)) / 15)
        End Function
        Public Shared Function GetBinFromHeure(ByVal Time As String) As Integer
            Dim oStrValue As String
            oStrValue = Time
            Return CInt(oStrValue.Split(":")(0)) * 4 + Math.Floor(CInt(oStrValue.Split(":")(1)) / 15)
        End Function

    End Class


End Class
